<template>
  <div class="config-group">
    <h4>饼图配置</h4>
    
    <!-- 基础配置 -->
    <div class="config-section">
      <div class="section-title">基础配置</div>
      <!-- 尺寸和背景 -->
      <div class="config-row">
        <div class="config-item">
          <label>宽度：</label>
          <input 
            type="text" 
            v-model="localConfig.width"
            @input="updateConfig"
            placeholder="例如：100%"
          >
        </div>
        <div class="config-item">
          <label>高度：</label>
          <input 
            type="text" 
            v-model="localConfig.height"
            @input="updateConfig"
            placeholder="例如：300px"
          >
        </div>
        <div class="config-item">
          <label>背景颜色：</label>
          <el-color-picker 
            v-model="localConfig.backgroundColor"
            show-alpha
            @change="updateConfig"
            size="small"
          />
        </div>
      </div>

      <!-- 数据来源 -->
      <div class="config-row">
        <div class="config-item">
          <label>数据来源：</label>
          <select v-model="dataSourceType" @change="handleDataSourceChange">
            <option value="static">静态数据</option>
            <option value="api">远程接口</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 饼图特有配置 -->
    <div class="config-section">
      <div class="section-title">饼图样式</div>
      
      <!-- 半径配置 -->
      <div class="config-row">
        <div class="config-item">
          <label>内半径：</label>
          <input 
            type="text" 
            v-model="localConfig.option.series[0].radius[0]"
            @input="updateConfig"
            placeholder="例如：0%"
          >
        </div>
        <div class="config-item">
          <label>外半径：</label>
          <input 
            type="text" 
            v-model="localConfig.option.series[0].radius[1]"
            @input="updateConfig"
            placeholder="例如：70%"
          >
        </div>
      </div>

      <!-- 玫瑰图配置 -->
      <div class="config-row">
        <div class="config-item">
          <label>玫瑰图：</label>
          <el-switch
            v-model="localConfig.option.series[0].roseType"
            @change="updateConfig"
          />
        </div>
      </div>

      <!-- 标签配置 -->
      <div class="config-row">
        <div class="config-item">
          <label>显示标签：</label>
          <el-switch
            v-model="localConfig.option.series[0].label.show"
            @change="updateConfig"
          />
        </div>
        <div class="config-item" v-if="localConfig.option.series[0].label.show">
          <label>标签位置：</label>
          <select 
            v-model="localConfig.option.series[0].label.position"
            @change="updateConfig"
          >
            <option value="outside">外部</option>
            <option value="inside">内部</option>
            <option value="center">中心</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 数据配置 -->
    <div class="config-section">
      <div class="section-title">数据配置</div>

      <!-- API配置 -->
      <div v-if="dataSourceType === 'api'" class="api-config">
        <div class="config-row">
          <div class="config-item">
            <label>接口地址：</label>
            <input 
              type="text"
              v-model="apiConfig.url"
              @input="handleApiConfigChange"
              placeholder="请输入接口地址"
            >
          </div>
        </div>

        <div class="config-row">
          <div class="config-item">
            <label>请求方法：</label>
            <select v-model="apiConfig.method" @change="handleApiConfigChange">
              <option value="GET">GET</option>
              <option value="POST">POST</option>
            </select>
          </div>
          <div class="config-item">
            <label>自动刷新：</label>
            <el-switch
              v-model="apiConfig.autoRefresh"
              @change="handleApiConfigChange"
            />
          </div>
          <div class="config-item" v-if="apiConfig.autoRefresh">
            <label>刷新间隔：</label>
            <input 
              type="number"
              v-model.number="apiConfig.refreshInterval"
              @input="handleApiConfigChange"
              min="1"
              placeholder="单位：秒"
            >
          </div>
        </div>

        <!-- 数据映射配置 -->
        <div class="mapping-config">
          <div class="mapping-example">
            <pre class="example-code">接口返回格式：
{
  "code": 200,
  "data": {
    "names": ["分类1", "分类2", "分类3"],
    "values": [120, 200, 150]
  }
}</pre>
          </div>
          <div class="config-row">
            <div class="config-item">
              <label>名称路径：</label>
              <input 
                type="text"
                v-model="apiConfig.mapping.names"
                @input="handleApiConfigChange"
                placeholder="例如：data.names"
              >
            </div>
            <div class="config-item">
              <label>数值路径：</label>
              <input 
                type="text"
                v-model="apiConfig.mapping.values"
                @input="handleApiConfigChange"
                placeholder="例如：data.values"
              >
            </div>
          </div>
        </div>

        <!-- 测试接口按钮 -->
        <div class="api-actions">
          <button class="test-api-btn" @click="testApi">测试接口</button>
        </div>
      </div>

      <!-- 静态数据配置 -->
      <div v-else class="static-data-config">
        <div class="series-config">
          <div class="series-header">
            <span>数据项配置</span>
            <button class="add-btn" @click="addDataItem">添加数据</button>
          </div>
          
          <div v-for="(item, index) in localConfig.option.series[0].data" 
               :key="index" 
               class="data-item">
            <div class="data-row">
              <div class="data-header">
                <span class="data-index">数据项 {{ index + 1 }}</span>
                <button 
                  v-if="localConfig.option.series[0].data.length > 1"
                  @click="removeDataItem(index)" 
                  class="remove-btn"
                >删除</button>
              </div>
            </div>
            
            <div class="data-content">
              <div class="config-item full-width">
                <label>名称：</label>
                <input 
                  type="text" 
                  v-model="item.name"
                  @input="updateConfig"
                  placeholder="数据名称"
                >
              </div>

              <div class="config-item full-width">
                <label>数值：</label>
                <input 
                  type="number" 
                  v-model.number="item.value"
                  @input="updateConfig"
                  placeholder="数据值"
                >
              </div>

              <div class="config-item">
                <label>颜色：</label>
                <el-color-picker 
                  v-model="item.itemStyle.color"
                  show-alpha
                  @change="updateConfig"
                  size="small"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'PieChartConfig',
  props: {
    config: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      localConfig: {
        width: '100%',
        height: '300px',
        backgroundColor: '#093443',
        option: {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            show: true,
            orient: 'horizontal',
            top: '5%',
            left: 'center',
            textStyle: {
              color: '#fff',
              fontSize: 12
            }
          },
          series: [{
            name: '饼图数据',
            type: 'pie',
            radius: ['0%', '70%'],
            center: ['50%', '50%'],
            roseType: false,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}: {d}%',
              color: '#fff'
            },
            data: [
              { name: '数据1', value: 335, itemStyle: { color: '#5470c6' } },
              { name: '数据2', value: 234, itemStyle: { color: '#91cc75' } },
              { name: '数据3', value: 158, itemStyle: { color: '#fac858' } }
            ]
          }]
        }
      },
      dataSourceType: 'static',
      apiConfig: {
        url: '',
        method: 'GET',
        autoRefresh: false,
        refreshInterval: 10,
        mapping: {
          names: 'data.names',
          values: 'data.values'
        }
      },
      refreshTimer: null
    }
  },
  created() {
    // 合并配置
    this.localConfig = {
      ...this.localConfig,
      ...this.config
    }
    
    // 设置数据源类型
    if (this.config.dataSourceType) {
      this.dataSourceType = this.config.dataSourceType
      if (this.dataSourceType === 'api' && this.config.apiConfig) {
        this.apiConfig = {
          ...this.apiConfig,
          ...this.config.apiConfig
        }
      }
    }
  },
  beforeDestroy() {
    this.clearRefreshTimer()
  },
  methods: {
    updateConfig() {
      const updatedConfig = {
        ...this.localConfig,
        dataSourceType: this.dataSourceType,
        apiConfig: this.dataSourceType === 'api' ? { ...this.apiConfig } : undefined
      }
      this.$emit('update:config', updatedConfig)
    },
    handleDataSourceChange() {
      if (this.dataSourceType === 'api') {
        this.setupApiConfig()
      } else {
        this.clearRefreshTimer()
      }
      this.updateConfig()
    },
    handleApiConfigChange() {
      this.resetRefreshTimer()
      this.updateConfig()
    },
    addDataItem() {
      const newItem = {
        name: `数据${this.localConfig.option.series[0].data.length + 1}`,
        value: 0,
        itemStyle: {
          color: this.getRandomColor()
        }
      }
      this.localConfig.option.series[0].data.push(newItem)
      this.updateConfig()
    },
    removeDataItem(index) {
      this.localConfig.option.series[0].data.splice(index, 1)
      this.updateConfig()
    },
    getRandomColor() {
      const colors = [
        '#5470c6', '#91cc75', '#fac858', '#ee6666',
        '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
      ]
      return colors[Math.floor(Math.random() * colors.length)]
    },
    async testApi() {
      try {
        await this.fetchApiData()
        this.$message.success('接口测试成功！')
      } catch (error) {
        this.$message.error('接口测试失败：' + error.message)
      }
    },
    async fetchApiData() {
      if (!this.apiConfig.url) return
      
      try {
        const response = await fetch(this.apiConfig.url, {
          method: this.apiConfig.method,
          headers: {
            'Content-Type': 'application/json'
          }
        })

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        const data = await response.json()
        
        // 获取数据
        const names = this.getValueByPath(data, this.apiConfig.mapping.names) || []
        const values = this.getValueByPath(data, this.apiConfig.mapping.values) || []

        // 更新图表数据
        this.localConfig.option.series[0].data = names.map((name, index) => ({
          name,
          value: values[index] || 0,
          itemStyle: {
            color: this.getRandomColor()
          }
        }))

        this.updateConfig()
      } catch (error) {
        console.error('获取远程数据失败:', error)
        throw error
      }
    },
    setupApiConfig() {
      if (this.apiConfig.url && this.apiConfig.autoRefresh) {
        this.resetRefreshTimer()
      }
    },
    resetRefreshTimer() {
      this.clearRefreshTimer()
      if (this.dataSourceType === 'api' && 
          this.apiConfig.autoRefresh && 
          this.apiConfig.refreshInterval > 0) {
        this.refreshTimer = setInterval(() => {
          this.fetchApiData()
        }, this.apiConfig.refreshInterval * 1000)
      }
    },
    clearRefreshTimer() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer)
        this.refreshTimer = null
      }
    },
    getValueByPath(obj, path) {
      return path.split('.').reduce((acc, part) => {
        return acc && acc[part]
      }, obj)
    }
  }
}
</script>

<style scoped>
.config-group {
  margin-bottom: 20px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.config-section {
  margin-bottom: 24px;
  padding: 20px;
  background: transparent;
  border-radius: 8px;
}

.section-title {
  font-size: 14px;
  color: #262626;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
  font-weight: 500;
}

.config-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 16px;
}

.config-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-item label {
  min-width: 80px;
  color: #595959;
}

.config-item input,
.config-item select {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  width: 120px;
}

.series-config {
  margin-top: 20px;
}

.series-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.add-btn {
  padding: 6px 12px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.data-item {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 12px;
  border: 1px solid #f0f0f0;
}

.data-row {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}

.data-row:last-child {
  margin-bottom: 0;
}

.data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.data-index {
  font-weight: 500;
  color: #262626;
}

.config-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-item.full-width {
  width: 100%;
}

.config-item.full-width input {
  flex: 1;
}

.remove-btn {
  padding: 4px 8px;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.remove-btn:hover {
  background: #ff7875;
}

.config-item input,
.config-item select {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  width: 120px;
}

.config-item.full-width input {
  width: auto;
}

:deep(.el-color-picker) {
  margin-right: 8px;
}

.mapping-example {
  background: #fafafa;
  padding: 16px;
  border-radius: 8px;
  margin: 16px 0;
}

.example-code {
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  font-family: monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #333;
  border: 1px solid #eee;
  margin: 0;
  white-space: pre-wrap;
}

.test-api-btn {
  padding: 8px 24px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.test-api-btn:hover {
  background: #40a9ff;
}

:deep(.el-switch) {
  margin-right: 8px;
}

:deep(.el-color-picker) {
  margin-right: 8px;
}

.data-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 12px;
}

.config-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-item.full-width {
  width: 100%;
}

.config-item.full-width input {
  flex: 1;
  min-width: 0;
}

.config-item label {
  min-width: 80px;
  color: #595959;
}

.config-item input {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  width: 120px;
}
</style> 